<template>
  <q-layout view="hHh Lpr lff">
    <q-header>
      <div class="bg-white row" style="flex-wrap: nowrap">
        <!-- 当是手机模式时（mobile）三条杠显示菜单按钮 -->
        <div class="q-ml-lg q-mt-sm mobileBtn" style="display: none">
          <q-btn
            dense
            round
            unelevated
            class="text-black"
            icon="menu"
            @click="menuClickShow"
          />
        </div>
        <!-- 复制头部标题到 q-header 标签内 -->
        <div class="headerShow" @dblclick="cutCompany">
          <div
            v-if="topTitle"
            class="text-center text-subtitle1 bg-primary"
            style="color: #fff; width: 230px; height: 50px; line-height: 50px;border:1px solid #367FA9"
          >
            光伏运维系统
          </div>
        </div>
        <div class="titleArea row justify-between items-center no-wrap">
          <div class="titleCon row no-wrap" style="width: 40%">
            <div class="q-ml-md row items-center">
              <q-icon name="menu" color="white" size="sm" @click="drawerClickTwo"/>
              <img :src="require('src/assets/newIcon/12.jpg')" class="q-ml-md"/>
              <span class="q-ml-sm" style="color:white">15°C</span>
            </div>
          </div>
          <q-space />
          <q-btn
            class="text-white headBtn"
            desend
            flat
            size="12px"
            color="white"
            icon="mdi-bell-outline"
            style="position: relative;"
          >
            <q-badge
              floating
              color="orange"
              rounded
              label="10"
              class="badge"
            />
          </q-btn>
          <q-btn
            class="text-white headBtn"
            desend
            flat
            icon="mdi-bullhorn-outline"
            size="12px"
            style="position: relative"
          >
            <q-badge
              floating
              color="red"
              rounded
              label="5"
              class="badge"
            />
          </q-btn>
          <div
            class="q-px-sm cursor-pointer user-name-container cursor-pointer"
            style="max-width: 230px"
          >
            <div class=" row no-wrap">
              <div class="userTop">
                <q-icon name="mdi-account-outline" size="sm"/>
              </div>
              <div style="white-space: nowrap">{{ user || "用户" }}</div>
            </div>
            <q-menu>
              <q-list>
                <q-item>
                  <q-item-section class="cursor-pointer" @click="logout"
                    >退出登录</q-item-section
                  >
                </q-item>
              </q-list>
            </q-menu>
          </div>
        </div>
      </div>
    </q-header>

    <q-drawer
      v-model="drawer"
      :mini="!drawer || miniState"
      @click.capture="drawerClick"
      show-if-above
      persistent
      class="bg-primary"
      :width="230"
      :mini-width="0"
    >
      <div class="fit">
        <!-- 左侧菜单列表 -->
        <q-list class="sidebar-container">
          <!-- 移动端下的菜单logo -->
          <q-item-label
            v-if="device === 'mobile'"
            class="text-center text-subtitle1 title-logo"
            style="color: #fff; width: 230px;border:1px solid red"
            @dblclick="cutCompany"
          >
            光伏运维系统
          </q-item-label>
          <div class="title-area">
            <EssentialLink
              :essentialLinks="essentialLinks"
              :initLevel="initLevel"
            />
          </div>
        </q-list>
      </div>
    </q-drawer>
    <q-page-container>
      <div>
        <div
          style="max-height: 50px"
          class="row no-wrap justify-between bg-white q-ml-md"
        >
          <div
            class="float-right relative-position nav;"
            style="
              width: 99%;
              height: 50px;
              line-height: 50px;
              border: 1px solid transparent;
              border-bottom-color: #009900;
            "
          >
            <q-breadcrumbs class="q-mr-md">
              <template v-slot:separator>
                <q-icon size="16px" name="chevron_right" color="grey" />
              </template>
              <q-breadcrumbs-el
                style="color: #666666"
                v-for="bread in levelList"
                :key="bread.meta.title"
                :label="bread.meta.title"
              />
            </q-breadcrumbs>
          </div>
        </div>
      </div>

      <router-view v-slot="{ Component }">
        <keep-alive>
          <component :is="Component" />
        </keep-alive>
      </router-view>
    </q-page-container>
  </q-layout>
  <q-dialog
    v-model="isGsShow"
    persistent
    @mousedown="dialogDrag($event, 1)"
    @mousemove="dragIcon($event)"
  >
    <q-card class="card-style" style="width: 300px">
      <q-card-section class="row items-center">
        <div class="text-h6">切换公司列表</div>
        <q-space />
        <q-btn icon="close" flat round dense @click="closeEbitUpdate"></q-btn>
      </q-card-section>
      <q-card-section>
        <q-table
          flat
          separator="none"
          :rows="dataList"
          :columns="columns"
          no-data-label="暂无数据"
          no-results-label="过滤器没有发现任何结果"
          row-key="name"
          v-model:pagination="pagination"
          hide-pagination
          :loading="loading"
        >
          <!-- 表格的加载状态 -->
          <template v-slot:loading>
            <q-inner-loading showing color="grey" />
          </template>
          <!-- 无数据提示信息 -->
          <template v-slot:no-data="{ message }">
            <div class="full-width row flex-center text-accent q-gutter-sm">
              <span>{{ message }}</span>
            </div>
          </template>
          <!-- 表格头部 -->
          <template v-slot:header="props">
            <q-tr
              :props="props"
              :class="
                themeColor.primary == '#FF9F03'
                  ? 'headTr'
                  : `${
                      themeColor.primary == '#004288'
                        ? 'headTrTwo'
                        : 'headTrThree'
                    }`
              "
            >
              <q-th v-for="col in props.cols" :key="col.name" :props="props">{{
                col.label
              }}</q-th>
            </q-tr>
          </template>
          <!-- 表格主体 -->
          <template v-slot:body="props">
            <q-tr :props="props" class="tableTr" @dblclick="GsTrClick(props)">
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <span>{{ col.value }}</span>
              </q-td>
            </q-tr>
          </template>
        </q-table>
        <!-- 分页
        <Pagination
            :pageSizes="['5条/页', '10条/页', '20条/页', '30条/页']"
            @updatePage="updatePage"
            @updateSizes="updateSizes"
            :pagination="pagination"
            @handlerRefresh="handlerRefresh"
        />-->
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script>
import EssentialLink from "components/EssentialLink";
import HeaderTab from "components/mainTab/headerTab.vue";
import ResizeMixin from "./mixin/ResizeHandler"; // 判断是移动端还是pc端
import drag from "src/components/mixins/drag.js";
import Pagination from "src/components/pagination";
// import BoardPreview from "./boardPreview.vue";

import { defineComponent, ref } from "vue";
import { mapGetters } from "vuex";
import HeadSearch from "src/components/mainTab/headSearch";
import Time from "src/components/mainTab/time";
import { getGSQX } from "src/api/reamtime.js";
import { getAerial } from "src/api/plant.js";
import { useRouter } from "vue-router";
import { routes } from "src/router/routes";

export default defineComponent({
  mixins: [ResizeMixin, drag],
  name: "MainLayout",
  components: {
    EssentialLink,
    // HeaderTab,
    // HeadSearch,
    // Time,
    // Pagination
  },
  data() {
    return {
      boardPreviewShow: false,
      drawer: false,
      miniState: false,
      isGsShow: false,
      loading: false,
      topTitle: true,
      menuContent: "<",
      show: 0,
      essentialLinks: [],
      nowPostionIdx: 1,
      dataList: [],
      columns: [
        {
          name: "company_name",
          label: "公司名称",
          align: "center",
          field: "company_name",
        },
      ],
      queryList: {
        page: 1,
        page_size: 10,
        ordering: "id",
      },
      pagination: {
        // 分页
        sortBy: "desc", // 列名
        descending: false, // 是否按照降序排序
        page: 1, // 页码（当前显示第几页的数据）
        rowsPerPage: 10, // 每页多少行
        rowsNumber: 10, // 共多少条
      },
      alarmData: {
        page: 1,
        page_size: 5,
        equip_id: "",
        state_type: 1,
        ordering: "-observe_time",
      },
      moreStatus: 0,
      moreIconShow: true,
      moreArr: [],
      moreArr2: [],
      aerial: {
        group: "all",
        ordering: "sequence",
        reverse: 0,
      },
    };
  },

  setup() {
    return {
      fixedMenu: [],
      imgUrl: [
        require("src/assets/menuRouter/j1.png"),
        require("src/assets/menuRouter/j2.png"),
        require("src/assets/menuRouter/j3.png"),
        require("src/assets/menuRouter/board.png"),
        require("src/assets/menuRouter/j7.png"),
        require("src/assets/menuRouter/j5.png"),
        require("src/assets/menuRouter/j6.png"),
        require("src/assets/menuRouter/j4.png"),
      ],
      user: localStorage.getItem("username_GFYW"),
      gsName: localStorage.getItem("gsName_GFYW"),
      levelList: ref([]),
      titlelogo: "机器效率",
      resizeShow: false,
      timer: null,
    };
  },
  computed: {
    // isShowRightMenu： 是否显示单个菜单  device：判断是pc还是移动端
    ...mapGetters([
      "initLevel",
      "uid",
      "routersArr",
      "themeColor",
      "isShowRightMenu",
      "device",
      "alarmNum",
      "msgNum",
    ]),
    key() {
      return this.$route.path;
    },
    // titleName() {
    //   return localStorage.getItem("titleName_GFYW").substr(0, 1);
    // },
  },
  watch: {
    routersArr: {
      immediate: true,
      deep: true,
      handler(val) {
        if (this.essentialLinks.length <= 0) {
          this.essentialLinks = [];
          if (this.routersArr && this.routersArr.length > 0) {
            this.routersArr.forEach((element) => {
              if (
                element &&
                element.meta &&
                element.meta.title &&
                element.children.length != 0
              ) {
                this.essentialLinks.push(element);
                this.fixedMenu.push(element.meta.fixedMenu);
                this.fixedMenu = [...new Set(this.fixedMenu)];
              }
            });
          } else {
            const _router = this.$router.options.routes;
            if (this.essentialLinks.length <= 0) {
              this.essentialLinks = [];
              if (_router.length > 0) {
                _router.forEach((element) => {
                  if (element.path === "/assetInfo") {
                    this.essentialLinks.push(element);
                  }
                });
              }
            }
          }
        }
      },
    },
    $route(route) {
    //   if (route.path == "/login") {
    //     this.nowPostionIdx = 0;
    //   } else {
    //     this.nowPostionIdx = 1;
    //   }
    //   if (route.path != "/boardOEE") {
    //     let metaEl = document.createElement("meta");
    //     metaEl.name = "viewport";
    //     metaEl.content =
    //       "width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover";
    //     document.firstElementChild.appendChild(metaEl);
    //     this.$store.commit("customMenu/RESIZE_SHOW", this.resizeShow);
    //   }
    //   if (
    //     route.path == "/realTimeState" ||
    //     route.path == "/workpiece" ||
    //     route.path == "/stantTime"
    //   ) {
    //     this.moreIconShow = true;
    //     // this.getMoreClick();
    //   } else {
    //     this.moreIconShow = false;
    //   }
      this.getBreadcrumb();
    },
  },
  created() {
    this.getBreadcrumb();
    // 如果是pc端，自动选择 有fixedMenu参数的第一个路由
    this.$nextTick(() => {
      // if (window.name == "") {
      //   let _firstRouter = this.essentialLinks.find(
      //     (element) => element && element.meta && element.meta.fixedMenu
      //   );
      //   if (!_firstRouter) this.clickIconMenu("首页");
      //   // this.clickIconMenu(_firstRouter.meta.fixedMenu);
      //   console.log("首次被加载", _firstRouter.meta.fixedMenu);
      //   window.name = "refresh";
      // } else if (window.name == "refresh") {
      //   this.clickIconMenu(this.$route.meta.fixedMenu);
      // }
    });
  },
  mounted() {
    // this.getAlarm();
    // this.setTimer();
  },
  methods: {
    // 点击更多图标传回数据
    getMoreClick() {
      getAerial(this.aerial).then((res) => {
        const { status, data } = res;
        this.moreArr = [];
        if (status == 200) {
          this.moreArr = this.moreArr.concat(data.all);
          this.moreArr2 = this.moreArr.concat(data.all);
        }
      });
    },
    moreClick(item) {
      if (item) {
        this.moreStatus = item;
        this.getMoreClick();
      } else {
        this.moreStatus = item;
      }
    },
    // 更多图标下背景色
    moreBgColor(item) {
      if (item.working_condition == -1) {
        return "background:#979797;";
      } else if (item.working_condition == 0) {
        return "background:#212A2C;";
      } else if (item.working_condition == 1) {
        return "background:#148A59;";
      } else if (item.working_condition == 2) {
        return "background:#FFC134;";
      } else if (item.working_condition == 5) {
        return "background:#CC0000;";
      }
    },
    // 更多机器下切换机器
    moreRoute(item) {
      let stateArr = {
        id: item.equip_id,
        name: item.equip_name,
      };
      this.$store.commit("customMenu/STATUS_ID", stateArr);
    },
    // 机器搜索传回数据
    searchItem(item) {
      this.moreArr = [];
      let arr = [];
      if (Object.keys(item).length != 0) {
        item.map((item) => {
          this.moreArr2.map((con) => {
            if (item.id == con.equip_id && item.name == con.equip_name) {
              arr.push(con);
            }
          });
        });
        let map = new Map();
        for (let con of arr) {
          if (!map.has(con.equip_id)) {
            map.set(con.equip_id, con);
          }
        }
        this.moreArr = [...map.values()];
      }
    },
    // 切换公司
    cutCompany() {
      this.dataList = [];
      this.loading = true;
      // this.queryList.page = this.pagination.page
      // this.queryList.page_size = this.pagination.rowsPerPage
      // 获取有权限公司列表
      getGSQX()
        .then((res) => {
          if (res.status == 200 && res.data.length >= 2) {
            res.data.map((item) => {
              let obj = {
                company_name: item.company_name,
                db: item.db,
                token: item.token,
                is_staff: item.is_staff,
                is_superuser: item.is_superuser,
              };
              this.dataList.push(obj);
            });
            this.isGsShow = true;
          }
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    GsTrClick(item) {
      this.$router.push({ path: "/realTimeState" });
      localStorage.setItem("token_key_GFYW", item.row.token);
      localStorage.setItem("db_GFYW", item.row.db);
      localStorage.setItem("gsName_GFYW", item.row.company_name);
      let data = {
        is_staff: item.row.is_staff,
        is_superuser: item.row.is_superuser,
      };
      this.$store.dispatch("login/getVisitMenu", data).then((res) => {
        window.name = "";
        location.reload();
      });
    },
    closeEbitUpdate() {
      this.isGsShow = false;
    },
    drawerClick(e) {
      if (this.miniState) {
        this.miniState = false;
        this.topTitle = true;
        this.resizeShow = !this.resizeShow;
        this.$store.commit("customMenu/RESIZE_SHOW", this.resizeShow);
        e.stopPropagation();
      }
    },
    drawerClickTwo() {
      this.miniState = !this.miniState;
      this.topTitle = !this.topTitle;
      this.resizeShow = !this.resizeShow;
      this.$store.commit("customMenu/RESIZE_SHOW", this.resizeShow);
    },
    menuClickShow() {
      this.drawer = !this.drawer;
    },
    // 警报跳转
    alarm() {
      this.$router.push("/informMangement");
    },
    // 获取警报消息信息
    getAlarm() {
      this.$store.dispatch("customMenu/alarm", "");
    },
    // 消息跳转
    msg() {
      this.$router.push("/msg");
    },
    // 定时器函数
    setTimer() {
      this.timer = setInterval(() => {
        this.getAlarm();
      }, 60000);
    },
    // 切换当前页数
    updatePage(val) {
      if (!val) return;
      this.pagination.page = val * 1;
      this.getTable();
    },
    // 切换每页的行数
    updateSizes(val) {
      this.pagination.rowsPerPage = parseFloat(val);
      this.getTable();
    },

    handlerRefresh() {
      this.handleResetSearch();
    },
    /**
     * 退出登录
     */
    async logout() {
      this.nowPostionIdx = 0;
      await this.$store.dispatch("login/logoutFun");
      clearInterval(this.timer);
      this.$router.push("/login");
      this.$store.commit("app/SET_VISITED_VIEWS"); //  清空可见tab标签
    },
    /**
     * 处理面包屑展示标题
     */
    getBreadcrumb() {
      this.levelList = this.$route.matched.filter(
        (item) => item.meta && item.meta.title
      );
      this.$store.commit("customMenu/LEVEL_LIST", this.levelList);
      if (Object.keys(this.levelList).length != 0) {
        this.clickIconMenu(this.levelList[0].meta.fixedMenu);
      }
      if (this.nowPostionIdx) {
        if (this.levelList.length != 0) {
          this.nowPostion = this.levelList[0].meta.fixedMenu;
        }
      }
    },
    /**
     * 全屏
     */
    toggleFullscreen() {
      this.$nextTick((_) => {
        const dom = document.body;
        this.$q.fullscreen
          .toggle(dom)
          .then((_) => {})
          .catch((error) => {
            console.log(error);
          });
      });
    },
    /**
     * 点击icon菜单（小菜单）
     * menuItem ： fixedMenu（菜单名称）
     */
    clickIconMenu(menuItem) {
      this.boardPreviewShow = false;
      if (menuItem == "机器") {
        this.titlelogo = "机器效率";
      } else if (menuItem == "系统") {
        this.titlelogo = "系统配置";
      } else if (menuItem == "后台") {
        this.titlelogo = "后台管理";
      } else if (menuItem == "生产") {
        this.titlelogo = "生产管理";
      } else if (menuItem == "配置") {
        this.titlelogo = "配置管理";
      } else if (menuItem == "警报") {
        this.titlelogo = "消息警报";
      } else if (menuItem == "看板") {
        this.titlelogo = "看板展示";
        this.boardPreviewShow = true;
      } else if (menuItem == "分析") {
        this.titlelogo = "报表统计";
      }
      this.$store.commit("customMenu/SET_IS_SHOW_RIGHT_MENU", menuItem);
    },
    // fontSize(name) {
    //   if (name.length >= 15) {
    //     return "font-size:14px;";
    //   }
    // },
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
});
</script>

<style lang="scss" scoped>
.moreCss {
  width: 97%;
  margin: 0 auto;
  color: white;
  font-size: 12px;

  div {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 70px;
    min-height: 48px;
    margin-left: 8px;
    margin-top: 10px;
    padding: 5px;
  }

  div:hover {
    transition: all 0.3s;
    border-radius: 4px;
    box-shadow: 1px 1px 5px black;
  }
}

.moreCss:after {
  content: "";
  flex: auto;
}

.user-name-container {
  height: 60px;
  line-height: 60px;
}

.user-name-container:hover {
  background: rgba(0, 0, 0, 0.025);
}

.meijia-title {
  background: #ffffff;
  border-right: 1px solid #ccc;
  box-shadow: 2px 2px 2px #ccc;
}

.meijia-hover {
  background: #f7f8ff;
}

.text-grey {
  color: #808080;
}

.bg-grey {
  background: #808080;
}

.titleArea {
  flex: 1;
  height: 50px;
  background: #009900;

  .titleCon {
    font-size: 16px;
    font-weight: bold;
    color: #30383f;
  }

  .titleConTwo {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: white;
    text-align: center;
    padding-left: 15px;
    padding-right: 15px;
    margin-left: 30px;
    min-width: 178px;
    height: 30px;
    line-height: 30px;
    background-image: url("assets/menuRouter/root@2x.png");
    background-position: center;
    background-size: 100%;
    background-repeat: no-repeat;
  }

  .time {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
    line-height: 60px;
  }

  .badge {
    position: absolute;
    top: 0px;
    right: 2px;
  }

  .userTop {
    color: white;
    text-align: center;
    font-size: 12px;
    border-radius: 50%;
    line-height: 20px;
    margin-top: 18px;
    margin-right: 5px;
  }
}

.titlelogo {
  height: 61px;
  font-size: 18px;
  font-family: PingFang-SC-Heavy, PingFang-SC;
  font-weight: 800;
  color: #b8b8b8;
  line-height: 61px;
  padding-left: 22px;
}

.menuClick {
  position: absolute;
  z-index: 11;
  top: 40%;
  right: -24px;
  width: 14px;
  height: 67px;
  color: white;
  cursor: pointer;
  border-left: 14px solid #212a2c;
  border-top: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;

  span {
    position: absolute;
    top: 15px;
    left: -10px;
  }
}

.bgColor {
  background: #212a2c;
}

@media (max-width: 370px) {
  ::v-deep(.headBtn) {
    .q-btn__content {
      display: inline-block;
    }
  }
}

@media (max-width: 500px) {
  .headBtn {
    width: 58px !important;
    height: 50px;
    padding-top: 7px;
  }

  .user-name-container {
    height: 50px;
  }

  .badge {
    position: absolute;
    top: 1px !important;
    right: 0px !important;
  }
}

@media (max-width: 606px) {
  .nav {
    display: none;
  }
}

@media (max-width: 796px) {
  .titleCon {
    display: none;
  }
}

@media (max-width: 1023px) {
  .titleCon {
    margin-top: 10px !important;
  }

  .headerShow,
  .menuClick {
    display: none;
  }

  .mobileBtn {
    display: block !important;
  }

  .fit {
    padding-top: 0px !important;
  }
}

@media (max-width: 1145px) {
  .titleConTwo {
    font-size: 12px !important;
  }
}

@media (max-width: 1450px) {
  .TimeShow {
    display: none;
  }

  .titleCon {
    width: 60% !important;
  }
}

.fit {
  overflow: scroll;
  overflow-x: hidden;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
